//
//  SEGServiceHotlineViewController.m
//  Commom
//
//  Created by 乔杨 on 2019/5/6.
//

#import "SEGServiceHotlineViewController.h"
#import "SEGServiceHotlineManager.h"
#import "SEGServiceHotlineCell.h"

#if __has_include(<Common/SEGPageSizeCustomerFlowLayout.h>)
#import <Commom/SEGPageSizeCustomerFlowLayout.h>
#else
#import "SEGPageSizeCustomerFlowLayout.h"
#endif
#if __has_include(<Common/SEGPageSizeCustomerCollectionView.h>)
#import <Common/SEGPageSizeCustomerCollectionView.h>
#else
#import "SEGPageSizeCustomerCollectionView.h"
#endif

@interface SEGServiceHotlineViewController ()<UICollectionViewDelegate, UICollectionViewDataSource ,UIScrollViewDelegate> {
    NSMutableDictionary *_hudParams;
}
/** 自定义导航 */
@property (nonatomic, strong) UIView *navBgView;
/** 导航返回按钮 */
@property (nonatomic, strong) UIButton *backBtn;
/** 导航标题 */
@property (nonatomic, strong) UILabel *titleLab;
/** 导航分割线 */
@property (nonatomic, strong) UIView *navLine;

/** 单项的宽度 */
@property (nonatomic, assign) CGFloat itemWidth;
@property (nonatomic, strong) SEGPageSizeCustomerFlowLayout *flowLayout;
@property (nonatomic, strong) SEGPageSizeCustomerCollectionView *collectionView;
/** 电话按钮 */
@property (nonatomic, strong) UIButton *phoneBtn;
/** 电话号码 */
@property (nonatomic, strong) NSString *phoneNum;
/** 全国监督服务热线 */
@property (nonatomic, strong) SEGLabel *phoneLab;
/** 全国监督服务热线号码 */
@property (nonatomic, copy) NSString *phoneString;

/** 请求类 */
@property (nonatomic, strong) SEGServiceHotlineManager *manager;

@end

@implementation SEGServiceHotlineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = kColor_W;
    self.phoneLab.hidden = YES;
    [self phoneLab_changeColor:kColor_2];
    
    // 当前页面的导航全为自定义
    self.navDisplayType = SEGNavigationBarDisplayTypeIgnore;
    [self seg_popGestureClose];
    self.navigationController.navigationBarHidden = YES;
    [self setUpUI];
    [self loadData];
    [self requestPhoneNumber];
}

#pragma mark - Load data
- (void)loadData {
    WeakSelf;
    [self.manager hotline_selectStewardPhoneWithFinished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        if (!isSuccessed) {
            [SEGAlertView showTmepMessageWithMessage:errorMessage];
            [weakSelf showNoContentViewAndChangeNavigationBarStyle];
            return;
        }
        if (weakSelf.manager.dataSourceArr.count <= 0) {
            [weakSelf showNoContentViewAndChangeNavigationBarStyle];
            return;
        }
        [weakSelf phoneLab_changeColor:kColor_2];
        weakSelf.phoneNum = weakSelf.manager.dataSourceArr[0].tel;
        [weakSelf.collectionView reloadData];
    }];
}
// 请求全国监督服务热线电话
- (void)requestPhoneNumber {
    if (self.phoneLab.hidden) return;
    WeakSelf;
    NSString *code = [NSString stringWithFormat:@"%@_service_tel",kAppPlatformCode]; //服务热线电话。
    [[SEGFindDictionaryInfoManagr sharedManager] requestDictionaryInfoByCode:code completed:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull codeType, NSString * _Nonnull errorMessage) {
        if (isSuccessed) {
            if ([result isKindOfClass:[NSDictionary class]] && [result[@"data"] isKindOfClass:[NSDictionary class]] && [result[@"data"][@"result"] isKindOfClass:[NSArray class]]) {
                NSArray *dataArray = result[@"data"][@"result"];
                if (dataArray.count > 0 && [[dataArray firstObject] isKindOfClass:[NSDictionary class]]) {
                    NSString *tel = [dataArray firstObject][@"type"];
                    if (tel.length > 0) {
                        weakSelf.phoneString = tel;
                        if (weakSelf.manager.dataSourceArr.count <= 0) {
                            [self phoneLab_changeColor:kColor_2];
                        } else {
                            [self phoneLab_changeColor:kColor_2];
                        }
                    }
                }
            }
        }
    }];
}

#pragma mark - UI
- (void)setUpUI {
    CGFloat topPadding = kNavigationBarAndStatusBarHeight + 10 * kScaleWidth;
    CGFloat viewHeight  = 355 * kScaleWidth;
    self.itemWidth = 302 * kScaleWidth;
    CGFloat itemHeight = viewHeight;
    self.collectionView = ({
        SEGPageSizeCustomerFlowLayout *layout = [[SEGPageSizeCustomerFlowLayout alloc] init];
        layout.type = SEGPageSizeCustomerFlowLayoutType_ServiceHotline;
        
        layout.itemSize = CGSizeMake(self.itemWidth, itemHeight);
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
        self.flowLayout = layout;
        SEGPageSizeCustomerCollectionView *collectionView = [[SEGPageSizeCustomerCollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.backgroundColor = UIColor.clearColor;
        [collectionView registerClass:[SEGServiceHotlineCell class] forCellWithReuseIdentifier:kSEGServiceHotlineCellIdentifier];
        [self.view addSubview:collectionView];
        collectionView;
    });
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(topPadding);
        make.height.mas_equalTo(viewHeight);
        make.left.right.equalTo(self.view);
    }];
    [self.view addSubview:self.phoneLab];
    [self.phoneLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(13);
        make.centerX.equalTo(self.view.mas_centerX);
        make.bottom.equalTo(self.view.mas_bottom).offset(-(25+LYSafeAreaBottom()));
    }];
    [self.view addSubview:self.phoneBtn];
    [self.phoneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.bottom.equalTo(self.phoneLab.mas_top).offset(-42);
    }];
    
    // 自定义导航
    [self.view addSubview:self.navBgView];
}
- (void)showNoContentViewAndChangeNavigationBarStyle {
    self.view.backgroundColor = kColor_W;
    // 自定义导航
    self.navBgView.backgroundColor = kColor_W;
    [self.backBtn setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"back")] forState:UIControlStateNormal];
    self.titleLab.textColor = kColor_1;
    self.navLine.hidden = NO;
    // 占位图
    _hudParams = [NSMutableDictionary dictionary];
    [_hudParams setObject:self.view forKey:(@"view")];
    [[SEGUhomeMediator sharedInstance] seg_showCustomProgressImage:_hudParams];
    self.collectionView.hidden = YES;
    self.phoneBtn.hidden = YES;
    [self phoneLab_changeColor:kColor_2];
    [self.view bringSubviewToFront:self.navBgView];
}

#pragma mark - <UICollectionViewDelegate, UICollectionViewDataSource>
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    self.collectionView.placeholderSV.contentSize = CGSizeMake(self.flowLayout.itemSize.width * self.manager.dataSourceArr.count, 0);
    return self.manager.dataSourceArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SEGServiceHotlineCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kSEGServiceHotlineCellIdentifier forIndexPath:indexPath];
    SEGServiceHotlineModel *model = self.manager.dataSourceArr[indexPath.row];
    [cell refreshCellWithModel:model];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat scrollviewWith = self.flowLayout.itemSize.width;
    [self.collectionView.placeholderSV setContentOffset:CGPointMake(indexPath.item * scrollviewWith, 0) animated:YES];
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat f = scrollView.contentOffset.x / (self.itemWidth);
    NSInteger index = (NSInteger)roundf(f);
    if (index < self.self.manager.dataSourceArr.count) { // 切换手机号
        SEGServiceHotlineModel *model = self.manager.dataSourceArr[index];
        self.phoneNum = model.tel;
    }
}

#pragma mark - Event
- (void)phoneBtnClick {
    if (@available(iOS 8.0, *)) {
        if (self.phoneNum.length > 0) {
            NSString *phone = [NSString stringWithFormat:@"telprompt://%@",self.phoneNum];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phone]];
        } else {
            [SEGAlertView showTmepMessageWithMessage:@"暂未更新管家联系方式"];
        }
    }
}
- (void)backBtnAction:(UIButton*)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Getter
- (UIView *)navBgView {
    if (!_navBgView) {
        _navBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 44+kStatusbarHeight)];
        _navBgView.backgroundColor = kColor_W;
        [_navBgView addSubview:self.backBtn];
        [_navBgView addSubview:self.titleLab];
        [_navBgView addSubview:self.navLine];
    }
    return _navBgView;
}
- (UIButton *)backBtn {
    if (!_backBtn) {
        UIImage *image = [UIImage imageWithContentsOfFile:SEGPicName(@"back")];
        _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _backBtn.frame = CGRectMake(17, kStatusbarHeight, image.size.width, image.size.height);
        [_backBtn setImage:image forState:UIControlStateNormal];
        [_backBtn addTarget:self
                     action:@selector(backBtnAction:)
           forControlEvents:UIControlEventTouchUpInside];
    }
    return _backBtn;
}
- (UILabel *)titleLab {
    if(!_titleLab) {
        _titleLab = [[UILabel alloc] init];
        _titleLab.frame = CGRectMake(100, kStatusbarHeight, self.navBgView.width-200, self.navBgView.height-kStatusbarHeight);
        _titleLab.font = kFont_16;
        _titleLab.textColor = kColor_1;
        _titleLab.text = self.titleString;
        _titleLab.textAlignment = NSTextAlignmentCenter;
    }
    return _titleLab;
}
- (UIView *)navLine {
    if (!_navLine) {
        _navLine = [[UIView alloc] initWithFrame:CGRectMake(0, self.navBgView.height-0.5, self.navBgView.width, 0.5)];
        _navLine.backgroundColor = [UIColor colorWithHexString:@"#E5E5E5"];
        _navLine.hidden = NO;
    }
    return _navLine;
}
- (SEGServiceHotlineManager *)manager {
    if (!_manager) _manager = [SEGServiceHotlineManager new];
    return _manager;
}
- (SEGLabel *)phoneLab {
    if (!_phoneLab) _phoneLab = [[SEGLabel alloc] init];
    return _phoneLab;
}
- (void)phoneLab_changeColor:(UIColor *)color {
    if (self.phoneLab.hidden) return;
    NSString *str1 = @"全国监督服务热线";
    NSString *defaultPhone = @"";
    NSString *str2 = self.phoneString ?: defaultPhone;
    
    NSString *str = [NSString stringWithFormat:@"%@%@",str1,str2];
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:str];
    text.yy_font = kFont_12;
    text.yy_color = color;
    NSRange range = [str rangeOfString:str2];
    [text yy_setTextHighlightRange:range
                             color:color
                   backgroundColor:[UIColor clearColor]
                         tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
                             if (@available(iOS 8.0, *)) {
                                 NSString *phone = [NSString stringWithFormat:@"telprompt://%@",str2];
                                 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phone]];
                             }
                         }];
    [text yy_setUnderlineStyle:NSUnderlineStyleSingle range:NSMakeRange(str1.length, str.length-str1.length)];
    self.phoneLab.attributedText = text;
    [self.view bringSubviewToFront:self.phoneLab];
}
- (UIButton *)phoneBtn {
    if (!_phoneBtn) {
        _phoneBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_phoneBtn setImage:[UIImage imageNamed:SEGPicName(@"btn_make_a_call")]
                   forState:UIControlStateNormal];
        [_phoneBtn setImage:[UIImage imageNamed:SEGPicName(@"btn_make_a_call")]
                   forState:UIControlStateHighlighted];
        [_phoneBtn addTarget:self
                      action:@selector(phoneBtnClick)
            forControlEvents:UIControlEventTouchUpInside];
    }
    return _phoneBtn;
}

@end
